package com.qhgrain.app.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.AppBusinessTypeEnum;
import com.qhgrain.app.service.AgentService;
import com.qhgrain.app.service.ApplicationService;
import com.qhgrain.app.service.MenuService;
import com.qhgrain.app.service.MyapplicationService;
import com.qhgrain.app.service.PermissionService;
import com.qhgrain.app.service.RoleService;
import com.qhgrain.app.service.UnitService;
import com.qhgrain.app.service.UserService;
import com.qhgrain.app.vo.AppVo;
import com.qhgrain.app.vo.MenuVo;
import com.qhgrain.app.vo.MyAppVo;
import com.qhgrain.app.vo.PermissionInfo;
import com.qhgrain.app.vo.RoleUnitVo;
import com.qhgrain.app.vo.RoleVo;
import com.qhgrain.app.vo.UserVo;

@Controller
@RequestMapping("/common")
public class CommonController {
	
	private static Logger LOG = LoggerFactory.getLogger(ApplicationController.class);
	
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private MyapplicationService myapplicationService;
	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UnitService unitService;
	@Autowired
	private AgentService agentService;
	/**
	 * 用户已安装的应用（用户常用应用）
	 * @param loginName
	 * @param appType 0web,1手机
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/get/installed/apps/nav",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getInstalApp(String loginName,String appType,HttpServletRequest request){
		JSONObject result = null;
		try {
			result = new JSONObject();
			if(StringUtil.isBlank(loginName)){
				throw new RuntimeException("根据loginName获取已安装应用，loginName不能为空");
			}
			UserVo user = this.userService.findByLoginName(loginName);
			if(user == null || StringUtil.isBlank(user.getUserId())){
				throw new RuntimeException("根据loginName获取已安装应用，loginName 找不到对应的用户");
			}
			String userId = user.getUserId();
			List<MyAppVo> myappList = this.myapplicationService.queryList(userId);
			
			JSONArray array = new JSONArray();
			JSONObject appJson = null;
			appType = StringUtil.isNotBlank(appType)?appType.trim():null;
			for(MyAppVo m : myappList){
				//内网门户过滤掉，不传，因为主页就是默认内网门户
				if("gway001".equals(m.getAppCode())){
					continue;
				}
				appJson = new JSONObject();
				appJson.put("appId", trim(m.getAppId()));
				appJson.put("appCode", trim(m.getAppCode()));
				appJson.put("text", trim(m.getAppName()));
				appJson.put("url", trim(m.getAppUrl()));
				appJson.put("iconClass",trim(m.getIconClass()));
				//群组名称，就是业务类型名称，就是说应用所属哪朵云
				appJson.put("appGroupName", trim(m.getBusinessTypeName()));
				appJson.put("appGroupType", trim(m.getBusinessType()));
				
				if(StringUtil.isBlank(appType)){
					array.add(appJson);
				}else if(appType.equals(m.getAppType())){
					array.add(appJson);
				}
			}
			result.put("data", array);
		} catch (Exception e) {
			result = new JSONObject();
			LOG.error("根据loginName获取其已安装（常用）应用出错...loginName="+loginName,e);
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 用户安装app
	 * @param loginName
	 * @param appId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/app/install",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String installApp(String loginName,String appId,HttpServletRequest request){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(loginName) || StringUtil.isBlank(appId)){
				result.put("code", "fail");
				result.put("msg","loginName或appId不能为空");
			}else{
				UserVo user = this.userService.findByLoginName(loginName);
				if(user == null || StringUtil.isBlank(user.getUserId())){
					result.put("code", "fail");
					result.put("msg", "根据loginName获取用户的userId是失败");
				}else{
					List<AppVo> appList = this.applicationService.getAll3(user.getUserId());
					boolean isCanInstall = false;
					if(appList != null && appList.size() > 0){
						for(AppVo a : appList){
							if(a.getId().equals(appId)){
								isCanInstall = true;
								break;
							}
						}
					}
					if(isCanInstall == false){
						result.put("code", "fail");
						result.put("msg", "该应用不属于你所在的应用群组，无法安装");
					}else{
						String userId = user.getUserId();
						boolean success = this.myapplicationService.add(userId, appId);
						if(success){
							result.put("code", "success");
							result.put("msg", "成功");
						}else{
							result.put("code", "fail");
							result.put("msg", "api添加已安装记录失败");
						}
					}
				}
			}
		} catch (Exception e) {
			LOG.error("用户安装应用失败...loginName="+loginName+",appId="+appId,e);
			result.put("code", "fail");
			result.put("msg", e.getMessage());
		}
		String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 删除已安装的
	 * @param loginName
	 * @param appId
	 * @return
	 */
	@RequestMapping(value="/app/delete",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String deleteApp(String loginName,String appId,HttpServletRequest request){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(loginName) || StringUtil.isBlank(appId)){
				result.put("code", "fail");
				result.put("msg","loginName或appId不能为空");
			}else{
				UserVo user = this.userService.findByLoginName(loginName);
				if(user == null || StringUtil.isBlank(user.getUserId())){
					result.put("code", "fail");
					result.put("msg", "根据loginName获取用户的userId是失败");
				}else{
					String userId = user.getUserId();
					boolean success = this.myapplicationService.deleteAndAdd(userId, Arrays.asList(appId), null);
					if(success){
						result.put("code", "success");
						result.put("msg", "成功");
					}else{
						result.put("code", "fail");
						result.put("msg", "api删除已安装记录失败");
					}
				}
					 
			}
		} catch (Exception e) {
			LOG.error("用户安装应用失败...loginName="+loginName+",appId="+appId,e);
			result.put("code", "fail");
			result.put("msg", e.getMessage());
		}
		String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	/**
	 * 根据登录名获取用户的应用市场集合（含是否安装信息）
	 * @param loginName 登录名
	 * @param appType 0 web,1手机
	 * @param appName
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/get/all/apps",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getAppNav(String loginName,String appType,String appName,HttpServletRequest request) {
		JSONObject result = null;
		try {
			result = new JSONObject();
			if(StringUtil.isBlank(loginName)){
				throw new RuntimeException("loginName");
			}else{
				UserVo user = this.userService.findByLoginName(loginName);
				if(user == null || StringUtil.isBlank(user.getUserId())){
					throw new RuntimeException("根据loginName获取用户的userId是失败");
				}else{
					String userId = user.getUserId();
					//用户已安装的常用应用
					List<MyAppVo> list1 = this.myapplicationService.queryList(userId);
					List<String> installedIds = new ArrayList<String>();
					if(list1 != null && list1.size()>0){
						for(MyAppVo v : list1){
							installedIds.add(v.getAppId());
						}
					}
					//用户所在群组所拥有的所有应用
					List<AppVo> list2 = this.applicationService.getAll3(userId);
					//内网门户过滤掉，不传，因为主页就是默认内网门户
					if(list2 != null && list2.size() > 0){
						List<AppVo> temp = new ArrayList<AppVo>();
						for(AppVo t : list2){
							if("gway001".equals(t.getAppCode())){
								continue;
							}
							temp.add(t);
						}
						list2 = temp;
					}
					
				
					
					//根据appName过滤
					List<AppVo> list3 = list2;
					appType = StringUtil.isNotBlank(appType)?appType.trim():null;
					appName = StringUtil.isNotBlank(appName)?URLDecoder.decode(appName).trim():null;
					//如果appName不为空，则根据appName过滤
					if(StringUtil.isNotBlank(appName) && list2 != null && list2.size()>0){
						list3 = new ArrayList<AppVo>();
						for(AppVo a : list2){
							if( a.getAppName().contains(appName)){
								list3.add(a);
							}
						}
					}
					//如果appType 不为空，则继续过滤
					if(StringUtil.isNotBlank(appType) && list3 != null && list3.size()>0){
						List<AppVo> list4 = new ArrayList<AppVo>();
						for(AppVo a : list3){
							if(appType.equals(a.getAppType())){
								list4.add(a);
							}
						}
						list3 = list4;
					}
					
					
					JSONArray dataArray = new JSONArray();
					if(list3 != null && list3.size() > 0){
						//对list3进行map归类
						Map<String,List<AppVo>> map = new LinkedHashMap<String,List<AppVo>>();
						for(AppBusinessTypeEnum e : AppBusinessTypeEnum.values()){
							List<AppVo> t = findAppVo(list3,e.getCode());
							if(t.size()>0){
								map.put(e.getName(), t);
							}
						}
						
						JSONObject jo1 = null;
						JSONArray  itemsArray = null;
						JSONObject jo2 = null;
						for(Map.Entry<String, List<AppVo>> m : map.entrySet()){
							jo1 = new JSONObject();
							jo1.put("type", m.getKey());
							jo1.put("sClass", "fa fa-cloud");
							
							itemsArray = new JSONArray();
							for(AppVo a : m.getValue()){
								jo2 = new JSONObject();
								jo2.put("text", trim(a.getAppName()));
								jo2.put("sClass", trim(a.getIconClass()));
								jo2.put("url", trim(a.getAppUrl()));
								jo2.put("appCode", trim(a.getAppCode()));
								jo2.put("appId", trim(a.getId()));
								jo2.put("isInstall", installedIds.contains(a.getId())?"1":"0");
								//群组名称，就是业务类型名称，就是说应用所属哪朵云
								jo2.put("appGroupName", trim(a.getBusinessTypeName()));
								jo2.put("appGroupType", trim(a.getBusinessType()));
								
								itemsArray.add(jo2);
							}
							jo1.put("items", itemsArray);
							
							dataArray.add(jo1);
						}
						
					}
					result.put("data", dataArray);
				}
			}
			
			
		} catch (Exception e) {
			LOG.error("根据loginName获取其对应的应用群组中的所有应用出错...",e);
			result = new JSONObject();
		}
		
		String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}

	/**
	 * 获取用户对指定应用的菜单集合
	 * @param loginName
	 * @param appId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/get/app/menus",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getMenus(String loginName,String appId,String appCode,HttpServletRequest request){
		JSONObject result = null;
		try {
			result = new JSONObject();
			if(StringUtil.isBlank(loginName) || (StringUtil.isBlank(appId) && StringUtil.isBlank(appCode))){
				throw new RuntimeException("loginName或appId/appCode不能为空");
			}else{
				UserVo user = this.userService.findByLoginName(loginName);
				if(user == null || StringUtil.isBlank(user.getUserId())){
					throw new RuntimeException("根据loginName获取用户的userId是失败");
				}else{
					if(StringUtil.isBlank(appId)){
						//根据appCode进行查找
						AppVo app = this.applicationService.findByAppCode(appCode.trim());
						if(app == null){
							throw new RuntimeException("根据appCode找不到对象信息");
						}
						appId = app.getId();
					}
					
					String userId = user.getUserId();
					List<MenuVo> list = this.menuService.getAll2(appId, userId, "0");
					
					JSONArray dataArray = new JSONArray();
					JSONObject m = null;
					if(list != null && list.size()>0){
						for(MenuVo v : list){
							m = new JSONObject();
							m.put("name", trim(v.getName()));
							m.put("url", trim(v.getMenuUrl()));
							m.put("id", trim(v.getId()));
							m.put("parentId", trim(v.getParentMenuId()));
							m.put("indexNumber", trim(v.getOrderNum()));
							
							dataArray.add(m);
						}
					}
				   result.put("data", dataArray);
				}
			}
		} catch (Exception e) {
			LOG.error("根据loginName="+loginName+",appId="+appId+"  appCode="+appCode+",获取菜单出错...",e);
			result = new JSONObject();
		}
		String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	
	private String trim(String s){
		return s == null?"":s.trim();
	}
	
	public List<AppVo> findAppVo(List<AppVo> list,String businessType){
		List<AppVo> list2 = new ArrayList<AppVo>();
		if(list != null && list.size()>0){
			for(AppVo v : list){
				if(businessType.equals(v.getBusinessType())){
					list2.add(v);
				}
			}
		}
		return list2;
	}
	/**
	 * 获取用户某应用下的所有权限
	 * @param loginName 登录名
	 * @param appId  应用id
	 * @param permissionType 权限类型，权限类型,"0"菜单权限，"1"功能权限，不传则表示获取全部
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/get/app/permissions",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getPermissions(String loginName,String appId,String appCode,String permissionType,HttpServletRequest request){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(loginName) || (StringUtil.isBlank(appId) && StringUtil.isBlank(appCode))){
				throw new RuntimeException("获取应用权限，loginName，appId/appCode不能为空");
			}
			UserVo user = this.userService.findByLoginName(loginName);
			if(user == null || StringUtil.isBlank(user.getUserId())){
				throw new RuntimeException("获取应用权限，loginName 找不到对应的用户");
			}
			
			if(StringUtil.isBlank(appId)){
				//根据appCode进行查找
				AppVo app = this.applicationService.findByAppCode(appCode.trim());
				if(app == null){
					throw new RuntimeException("根据appCode找不到对象信息");
				}
				appId = app.getId();
			}
			
			String userId = user.getUserId();
			List<PermissionInfo> permissonList = this.permissionService.queryByUserApp(userId, appId, permissionType);
			
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data", JSON.toJSON(permissonList).toString());
			
		} catch (Exception e) {
			LOG.error("获取应用权限出错...loginName="+loginName+"  appId="+appId+"   appCode="+appCode,e);
			
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	/**
	 * 获取某角色下的某应用的权限
	 * @param loginName 登录名
	 * @param appId  应用id
	 * @param permissionType 权限类型，权限类型,"0"菜单权限，"1"功能权限，不传则表示获取全部
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/get/role/app/permissions",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getRoleAppPermissions(String roleId,String roleCode,String appId,String appCode,String permissionType,HttpServletRequest request){
		JSONObject result = new JSONObject();
		try {
			if((StringUtil.isBlank(roleId)&&StringUtil.isBlank(roleCode)) || (StringUtil.isBlank(appId) && StringUtil.isBlank(appCode))){
				throw new RuntimeException("获取应用权限，roleId/roleCode，appId/appCode不能为空");
			}
			
			if(StringUtil.isBlank(appId)){
				//根据appCode进行查找
				AppVo app = this.applicationService.findByAppCode(appCode.trim());
				if(app == null){
					throw new RuntimeException("根据appCode找不到对象信息");
				}
				appId = app.getId();
			}
			
			if(StringUtil.isBlank(roleId)){
				//根据appCode进行查找
				RoleVo role = this.roleService.findByRoleCode(roleCode);
				
				if(role == null){
					throw new RuntimeException("根据roleCode找不到对象信息");
				}
				roleId = role.getId();
			}
			
			
			List<PermissionInfo> permissonList = this.permissionService.queryByRoleApp(roleId, appId, permissionType);
			
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data", JSON.toJSON(permissonList).toString());
			
		} catch (Exception e) {
			LOG.error("获取角色-应用权限出错...roleId="+roleId+"  roleCode="+roleCode+"  appId="+appId+"  appCode="+appCode,e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	/**
	 * 获取用户所有的角色
	 * @param request
	 * @param loginName
	 * @return
	 */
	@RequestMapping(value="/get/user/roles" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserRoles(HttpServletRequest request,String loginName){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(loginName) ){
				throw new RuntimeException("获取用户所有的角色，loginName不能为空");
			}
			UserVo user = this.userService.findByLoginName(loginName);
			if(user == null || StringUtil.isBlank(user.getUserId())){
				throw new RuntimeException("获取用户所有的角色，loginName 找不到对应的用户");
			}
			String userId = user.getUserId();
			com.alibaba.fastjson.JSONArray roles = this.roleService.getAll(userId);
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data", roles.toString());
			
		} catch (Exception e) {
			LOG.error("获取用户所有的角色出错...loginName="+loginName,e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	
	
	
	
	/**
	 * 获取用户-应用-组织
	 * @param loginName
	 * @param appId
	 * @return
	 */
	@RequestMapping(value="/get/user/app/units" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserAppUnit(HttpServletRequest request , String loginName,String appId,String appCode){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(loginName) || (StringUtil.isBlank(appId) && StringUtil.isBlank(appCode)) ){
				throw new RuntimeException("获取用户-应用-组织，loginName，appId/appCode不能为空");
			}
			UserVo user = this.userService.findByLoginName(loginName);
			if(user == null || StringUtil.isBlank(user.getUserId())){
				throw new RuntimeException("获取用户用户-应用-组织，loginName 找不到对应的用户");
			}
			
			if(StringUtil.isBlank(appId)){
				//根据appCode进行查找
				AppVo app = this.applicationService.findByAppCode(appCode.trim());
				if(app == null){
					throw new RuntimeException("根据appCode找不到对象信息");
				}
				appId = app.getId();
			}
			
			String userId = user.getUserId();
			RoleUnitVo ru = this.unitService.getRoleUnitByUser(userId, appId);
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data",ru!=null && ru.getUnitList() != null? JSON.toJSON(ru.getUnitList()) : new JSONArray());
			
		} catch (Exception e) {
			LOG.error("获取用户-应用-组织出错...loginName="+loginName,e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	
	/**
	 * 获取角色-应用-组织
	 * @param loginName
	 * @param appId
	 * @return
	 */
	@RequestMapping(value="/get/role/app/units" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getRoleAppUnit(HttpServletRequest request , String roleId,String roleCode,String appId,String appCode){
		JSONObject result = new JSONObject();
		try {
			
			if((StringUtil.isBlank(roleId)&&StringUtil.isBlank(roleCode)) || (StringUtil.isBlank(appId) && StringUtil.isBlank(appCode))){
				throw new RuntimeException("根据业务角色，应用获取组织，roleId/roleCode，appId/appCode不能为空");
			}
			
			if(StringUtil.isBlank(appId)){
				//根据appCode进行查找
				AppVo app = this.applicationService.findByAppCode(appCode.trim());
				if(app == null){
					throw new RuntimeException("根据appCode找不到对象信息");
				}
				appId = app.getId();
			}
			
			if(StringUtil.isBlank(roleId)){
				//根据appCode进行查找
				RoleVo role = this.roleService.findByRoleCode(roleCode);
				
				if(role == null){
					throw new RuntimeException("根据roleCode找不到对象信息");
				}
				roleId = role.getId();
			}
			
			RoleUnitVo ru = this.unitService.getRoleUnitByRole(roleId, appId);
			
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data",ru!=null && ru.getUnitList() != null? JSON.toJSON(ru.getUnitList()) : new JSONArray());
			
		} catch (Exception e) {
			LOG.error("根据业务角色，应用获取组织系统出错...",e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 根据组织和角色获取对应的所有用户(是否包含下级)
	 * @param roleId
	 * @param roleCode
	 * @param unitId
	 * @param isContainNextLevel 0表示不包含下级用户，1表示包含，不传默认不包含
	 * @return
	 */
	@RequestMapping(value="/get/unit/role/users" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUsersByRoleAndUnit(HttpServletRequest request,String roleId,String roleCode,String unitId,String isContainNextLevel){
		net.sf.json.JSONObject result = new net.sf.json.JSONObject();
		try {
			
			if((StringUtil.isBlank(roleId)&&StringUtil.isBlank(roleCode)) || StringUtil.isBlank(unitId)){
				throw new RuntimeException("根据业务角色，应用获取组织，roleId/roleCode，unitId不能为空");
			}
			boolean _isContainNextLevel = false;
			if("1".equals(isContainNextLevel)){
				_isContainNextLevel = true;
			}
			List<UserVo> list = this.userService.getUsersByRoleAndUnit(roleId, roleCode, unitId,_isContainNextLevel);
			
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("data",list != null? net.sf.json.JSONArray.fromObject(list) : new JSONArray());
			
		} catch (Exception e) {
			LOG.error("根据组织和角色获取对应的所有用户系统出错...",e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 根据用户名、组织，分页查询用户
	 * @param request
	 * @param userName
	 * @param unitId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="/get/users/page" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUsersPage(HttpServletRequest request,String userName,String unitId,String pageNum,String pageSize){
		net.sf.json.JSONObject result = new net.sf.json.JSONObject();
		try {
			int num = StringUtil.isNotBlank(pageNum)?Integer.parseInt(pageNum):1;
			int size = StringUtil.isNotBlank(pageSize)?Integer.parseInt(pageSize):10;
			
			PageBean<UserVo> pageBean = this.userService.queryPage(userName, null, unitId, null, null, null, "1", num, size	);
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("list",pageBean.getData() != null? net.sf.json.JSONArray.fromObject(pageBean.getData()) : new JSONArray());
			result.put("totalCount", pageBean.getTotalCount());
		} catch (Exception e) {
			LOG.error("根据组织和角色获取对应的所有用户系统出错...",e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 根据角色编码获取所有用户
	 * @param request
	 * @param roleCode
	 * @return
	 */
	@RequestMapping(value="/get/role/users" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUsersByRole(HttpServletRequest request,String roleCode,String roleId){
		net.sf.json.JSONObject result = new net.sf.json.JSONObject();
		try {
			if(StringUtil.isBlank(roleCode)&&StringUtil.isBlank(roleId)){
				throw new RuntimeException("根据角色编码获取所有用户,roleId/roleCode不能为空");
			}
		
			if(StringUtil.isBlank(roleId)){
				//根据appCode进行查找
				RoleVo role = this.roleService.findByRoleCode(roleCode);
				if(role == null){
					throw new RuntimeException("根据roleCode找不到对象信息");
				}
				roleId = role.getId();
			}
			
			List<UserVo> list = this.userService.getUsersByRoleId(roleId);
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("list",list != null?list:new JSONArray());
		} catch (Exception e) {
			LOG.error("根据角色编码获取所有用户...roleCode="+roleCode,e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 根据应用获取角色
	 * @param request
	 * @param appCode
	 * @return
	 */
	@RequestMapping(value="/get/app/roles" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getRolesByApp(HttpServletRequest request,String appCode){
		net.sf.json.JSONObject result = new net.sf.json.JSONObject();
		try {
			if(StringUtil.isBlank(appCode)){
				throw new RuntimeException("根据应用获取角色,appCode不能为空");
			}
			String appId = null;
			//根据appCode进行查找
			AppVo app = this.applicationService.findByAppCode(appCode.trim());
			if(app == null){
				throw new RuntimeException("根据appCode找不到对象信息");
			}
			appId = app.getId();
			
			List<RoleVo> list = this.roleService.getRolesByApp(appId);
			result.put("code", "1");
			result.put("msg", "成功");
			result.put("list",list != null?list:new JSONArray());
		} catch (Exception e) {
			LOG.error("根据应用获取角色系统出错...appCode="+appCode,e);
			result.put("code", "0");
			result.put("msg", e.getMessage());
		}
		 String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  

		return jsonpCallback+"("+result.toString()+")";
	}
	/**
	 * 修改用户密码
	 * @param userName
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value="/user/changePassword",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String changeUserPassword(String userName, String oldPassword, String newPassword, HttpServletRequest request, HttpServletResponse response){
		net.sf.json.JSONObject resJson = new net.sf.json.JSONObject();
		
		try{
			if(StringUtils.isBlank(userName)||StringUtils.isBlank(oldPassword)|| StringUtils.isBlank(newPassword)){
				throw new IllegalAccessException("用户名或新旧密码不能为空");
			}
			if(newPassword.length()<6){
				throw new IllegalAccessException("密码不能少于6位");
			}
			String resIAM = this.agentService.changeUserPassword(userName, oldPassword, newPassword);
			System.out.println(resIAM);
			net.sf.json.JSONObject resJsonIAM = net.sf.json.JSONObject.fromObject(resIAM);
			resJson.put("code", resJsonIAM.get("result").toString());
			resJson.put("msg", resJsonIAM.get("message"));
		}catch (IllegalAccessException e){
			resJson.put("code", "0");
			resJson.put("msg", e.getMessage());
			
		}catch (Exception e){
			resJson.put("code", "0");
			resJson.put("msg", "系统错误,操作失败");
			LOG.error(e.getMessage());
		}
		response.addHeader("Access-Control-Allow-Origin", "*");	
		return resJson.toString();
	}
}
